
import numpy as np
import matplotlib.tri as mtri
from mayavi import mlab

def generate_terrain(size=100):
    """生成模拟山地地形"""
    x = np.linspace(-5, 5, size)
    y = np.linspace(-5, 5, size)
    xx, yy = np.meshgrid(x, y)
    
    # 组合多个周期函数创建复杂地形
    z = (np.sin(xx**2 + yy**2) * 0.5 + 
         np.cos(2*xx + 1) * 0.3 +
         np.exp(-(xx**2 + yy**2)/8) * 2)
    return xx.flatten(), yy.flatten(), z.flatten()

def create_tin(x, y, z, density=0.3):
    """构建不规则三角网"""
    points = np.column_stack((x, y))
    tri = mtri.Triangulation(x, y)
    return tri.triangles

def visualize_terrain(x, y, z, triangles):
    """交互式3D可视化"""
    mlab.figure(bgcolor=(1,1,1), size=(800,600))
    mesh = mlab.triangular_mesh(x, y, z, triangles,
                              colormap='gist_earth',
                              representation='wireframe')
    mlab.colorbar(mesh, title='Elevation')
    mlab.view(azimuth=45, elevation=60)
    mlab.show()

if __name__ == "__main__":
    x, y, z = generate_terrain(50)
    triangles = create_tin(x, y, z)
    visualize_terrain(x, y, z, triangles)
